import { createAsyncThunk, createSlice, PayloadAction } from '@reduxjs/toolkit';
import { ReduxState } from '..';
import { getDevProperty, saveDevProperty } from '@ray-js/ray';
import { utils } from '@ray-js/panel-sdk';
import { getCachedLaunchOptions } from '@/api/getCachedLaunchOptions';
import { cloneDeep } from 'lodash-es';
import Strings from '@/i18n';

export const DEV_PROPERTIES = {
  GROUP_ICONS: 'GROUP_ICONS',
};
type DeviceAttr = {
 
  attrs: Array<{ code: string; value: string }>;

}
type attrInfo = keyof DeviceAttr;
const DEFAULT_GROUP_ICONS = [
  { code: 'oilTotal', value: "250ML" },
  { code: 'aromatherapyType',  value:"0" },
  { code: 'aromatherapyType1', value: ""},
  { code: 'aromatherapyType2', value: "" },
  { code: 'aromatherapyType3', value: "" },
  { code: 'aromatherapyType4', value: "" },

];

/**
 * Slice
 */
/**
 * Redux slice for managing custom UI image states in a four-way panel
 * Contains state for different device types (lighting, switch, curtain, aircondition, fan)
 * with 4 image states each (numbered 1-4)
 * 
 * @state {customInfo_ts} Initial state with all image values set to 0
 * @reducers Provides setters for updating individual image states:
 * - setLightingImage1-4
 * - setSwitchImage1-4
 * - setCurtainImage1-4  
 * - setAirconditionImage1-4
 * - setFanImage1
 */
const customSlice = createSlice({
  name: 'attrInfo',
  initialState: {

    attrs: DEFAULT_GROUP_ICONS,

  } as DeviceAttr,
  reducers: {
   
    initAttrs(state, action: PayloadAction<{ groupIcons: DeviceAttr['attrs'] }>) {
      state.attrs = action.payload.groupIcons;
    
    },
    updateAttrs(state, action: PayloadAction<{ groupIcons: DeviceAttr['attrs'] }>) {
      state.attrs = action.payload.groupIcons;
    },
  },
});
const { deviceId } = getCachedLaunchOptions().query;


/**
 * Actions
 */


/**
 * Selectors
 */
export const customInfo = (state: ReduxState) => state.attrs;

type SelectCustomInfoByKey = <T extends attrInfo>(
  dpCode: T
) => (state: ReduxState) => DeviceAttr[T];
export const selectCustomInfoByKey: SelectCustomInfoByKey = key => state => state.attrs[key];
/**
 * Selectors
 */
/**
 * Selector function to retrieve device icons from the Redux store.
 * @param state - The Redux state object.
 * @returns The device icons attributes from the attrs slice of state.
 */
export const selectAttrs = (state: ReduxState) => state.attrs.attrs;
export default customSlice.reducer;
export const getAttrsAsync = createAsyncThunk<DeviceAttr['attrs']>(
  'attrInfo/getAttrsAsync',
  async (__, thunkApi) => {
    const res = (await getDevProperty({
      devId: deviceId,
      code: DEV_PROPERTIES.GROUP_ICONS,
      bizType: 0,
    })) as unknown as DeviceAttr['attrs'];
    console.log("getAttrsAsync:", res)
    const groupIcons =
      !res || res.length === 0
        ? DEFAULT_GROUP_ICONS
        : (utils.parseJSON(res?.[0]?.value.toString()) as unknown as DeviceAttr['attrs']);
    console.log("getAttrsAsync:", groupIcons)

    thunkApi.dispatch(customSlice.actions.initAttrs({ groupIcons }));

    return res;
  }
);

export const updateAttrsAsync = createAsyncThunk<boolean, { code: string; value: string }>(
  'attrInfo/updateAttrsAsync',
  async (param, thunkApi) => {
    const state = thunkApi.getState() as ReduxState;
    const { code, value } = param;
    console.log('updateAttrsAsync:', code, value);
    const groupIcons = cloneDeep(state.attrs.attrs) as DeviceAttr['attrs'];
    const targetGroup = groupIcons.find(item => item.code === code);
    if (!targetGroup) {
      return false;
    }
    targetGroup.value = value;
    console.log('updateAttrsAsync:', targetGroup);
    const res = await saveDevProperty({
      devId: deviceId,
      bizType: 0,
      propertyList: JSON.stringify([{ code: DEV_PROPERTIES.GROUP_ICONS, value: groupIcons }]),
    });
    thunkApi.dispatch(customSlice.actions.updateAttrs({ groupIcons }));
    return res;
  }
);
export const updateAttrsExAsync = createAsyncThunk<boolean,{ code: string; value: string } []>(
  'attrInfo/updateAttrsAsync',
  async (param, thunkApi) => {
    const state = thunkApi.getState() as ReduxState;
   
    console.log('updateAttrsExAsync param:',param);
    const attress = cloneDeep(state.attrs.attrs) as DeviceAttr['attrs'];
    param.forEach(item => {
      const targetGroup = attress.find(_item => _item.code === item.code);
      if (targetGroup) {
        targetGroup.value = item.value;
      }
    });
    console.log('updateAttrsExAsync:',attress);
 
    const res = await saveDevProperty({
      devId: deviceId,
      bizType: 0,
      propertyList: JSON.stringify([{ code: DEV_PROPERTIES.GROUP_ICONS, value: attress }]),
    });
    thunkApi.dispatch(customSlice.actions.updateAttrs({ groupIcons:attress }));
    return res;
  }
);